<template>
  <i-dialog
    title="编辑标签"
    :visible="visible"
    width="642px"
    :close-on-click-modal="false"
    @close="outerClose"
  >
    <i-form
      :items="formItems"
      :model="form"
      :rules="rules"
      ref="form"
      label-width="95px"
      class="demo-form"
    >
    </i-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="outerClose">取 消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </span>
  </i-dialog>
</template>
<script>
import formValidate from '@/utils/validate'
import { updateDeviceLabel } from '@/api/device'
export default {
  name: 'EditLabel',
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    deviceAttr: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      form: {
        label: this.deviceAttr.label,
      },
      formItems: [
        {
          type: 'text',
          value: 'label',
          label: '设备标签',
          clearable: true,
        },
      ],
      rules: {
        label: [
          {
            max: 20,
            message: '最多允许输入20个字符',
            trigger: ['change', 'blur'],
          },
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
      },
    }
  },
  methods: {
    outerClose() {
      this.form = {}
      this.$emit('update:visible', false)
    },
    refreshTable() {
      this.$emit('refreshTable')
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          updateDeviceLabel({
            ...this.form,
            deviceId: this.deviceAttr.deviceId,
          }).then(() => {
            this.refreshTable()
            this.outerClose()
          })
        }
      })
    },
  },
}
</script>
